import { defineComponent, ref } from 'vue'
import {
  FormInst,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NModal,
  useMessage
} from 'naive-ui'
import styles from './modal-handle.module.scss'
import { useRouter } from 'vue-router'
import { createRuleGroupData } from '@/service/modules/integration-monitor'

const props = {
  propModal: {
    type: Boolean,
    default: true
  }
}

const createRuleGroup = defineComponent({
  name: 'createRuleGroup',
  props,
  emits: ['closeModal', 'updateRuleGroup'],
  setup(props, { emit }) {
    const router = useRouter()

    const ruleGroupForm = ref({
      hiveDatabase: router.currentRoute.value.query.schemaName,
      hiveTableName: router.currentRoute.value.query.tableName,
      name: ''
    })

    const rules = {
      hiveDatabase: {},
      hiveTableName: {},
      name: { required: true, message: '请输入规则组名', trigger: 'blur' }
    }

    const onCloseModal = function () {
      emit('closeModal', true)
    }

    const ruleGroupSubmit = function (e: MouseEvent) {
      e.preventDefault()
      formRef.value?.validate((errors) => {
        if (!errors) {
          // @ts-ignore
          createRuleGroupData(ruleGroupForm.value)
            .then((res: any) => {
              emit('updateRuleGroup')
              emit('closeModal')
              message.success(res.msg ? res.msg : '创建成功')
            })
            .catch((err: any) => {
              message.error(err.msg ? err.msg : '接口未知错误')
            })
        }
      })
    }

    const message = useMessage()

    const formRef = ref<FormInst | null>(null)

    return {
      ruleGroupForm,
      router,
      rules,
      onCloseModal,
      ruleGroupSubmit,
      message,
      formRef
    }
  },
  render() {
    return (
      <NModal
        v-model:show={this.$props.propModal}
        preset='card'
        class={styles['modal-handle']}
        title='新建规则组'
        size='huge'
        bordered={false}
        on-close={this.onCloseModal}
      >
        <NForm
          model={this.ruleGroupForm}
          rules={this.rules}
          label-placement='left'
          ref={'formRef'}
        >
          <NFormItem label='规则集合名称' path='name' label-width='120px'>
            <NInput
              v-model:value={this.ruleGroupForm.name}
              placeholder='请输入规则集合名称'
            ></NInput>
          </NFormItem>
          <NFormItem>
            <NButton onClick={this.ruleGroupSubmit}>立即创建</NButton>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default createRuleGroup
